using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CaseData;

namespace CaseManager{

    public partial class CaseManager : Form {
        CaseDataAccess cdAccess;
        DataGridView m_activeGrid;
        string m_currentFile;

        public CaseManager(){
            InitializeComponent();
            cdAccess = new CaseDataAccess();
            SetGridProperties(gvAllCases);
            SetGridProperties(gvNewCases);
            SetGridProperties(gvCustomerContacted);
            SetGridProperties(gvPendingRepair);
            SetGridProperties(gvPendingApproval);
            SetGridProperties(gvPendingDelivery);
            SetGridProperties(gvInProgress);
            SetGridProperties(gvFollowUp);
            SetGridProperties(gvClosed);

            //cdAccess.ReadImportedDataTable(@"C:\Documents and Settings\Carl\Desktop\JoAnne's Tracker.xls");
        }
        public CaseManager ( string fileName ) {
            InitializeComponent();
            cdAccess = new CaseDataAccess();
            SetGridProperties(gvAllCases);
            SetGridProperties(gvNewCases);
            SetGridProperties(gvCustomerContacted);
            SetGridProperties(gvPendingRepair);
            SetGridProperties(gvPendingApproval);
            SetGridProperties(gvPendingDelivery);
            SetGridProperties(gvInProgress);
            SetGridProperties(gvFollowUp);
            SetGridProperties(gvClosed);
            cdAccess = new CaseDataAccess(fileName);
            PopulateCases();
            saveToolStripMenuItem.Enabled = false;

            //cdAccess.ReadImportedDataTable(@"C:\Documents and Settings\Carl\Desktop\JoAnne.xls");
        }

        public bool PromptSave {
            get { return saveToolStripMenuItem.Enabled; }
            set { saveToolStripMenuItem.Enabled = value; }
        }

        private void PopulateCases ( ) {
            PopulateGridView(gvAllCases, cdAccess.AllCases);
            PopulateGridView(gvNewCases, cdAccess.NewCases);
            PopulateGridView(gvCustomerContacted, cdAccess.CustomerContactedCases);
            PopulateGridView(gvPendingRepair, cdAccess.PendingRepairCases);
            PopulateGridView(gvPendingApproval, cdAccess.PendingApprovalCases);
            PopulateGridView(gvPendingDelivery, cdAccess.PendingDeliveryCases);
            PopulateGridView(gvInProgress, cdAccess.InProgressCases);
            PopulateGridView(gvFollowUp, cdAccess.FollowUpCases);
            PopulateGridView(gvClosed, cdAccess.ClosedCases);
            m_activeGrid = gvAllCases;
            CountRows();
        }

        private void PopulateGridView ( DataGridView gvOnTab, DataView dvOnTab ) {
            // Set up the grid columns
            gvOnTab.AutoGenerateColumns = false;
            gvOnTab.DataSource = dvOnTab;

        }

        private void SetGridProperties ( DataGridView gvOnTab ) {

            int newColIndex = gvOnTab.Columns.Add("TicketId", "Ticket Id");
            gvOnTab.Columns[newColIndex].DataPropertyName = "TicketId";
            gvOnTab.Columns[newColIndex].ReadOnly = true;

            DataGridViewComboBoxColumn cmbWhereFrom = new DataGridViewComboBoxColumn();
            cmbWhereFrom.DataPropertyName = "WhereFromId";
            cmbWhereFrom.DataSource = cdAccess.WhereFromList;
            cmbWhereFrom.ReadOnly = false;
            cmbWhereFrom.DisplayMember = "Name";
            cmbWhereFrom.ValueMember = "WhereFromInt";
            cmbWhereFrom.HeaderText = "Where From";
            cmbWhereFrom.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

            DataGridViewComboBoxColumn cmbStatus = new DataGridViewComboBoxColumn();
            cmbStatus.DataPropertyName = "CaseStatusId";
            cmbStatus.DataSource = cdAccess.CaseStatusList;
            cmbStatus.ReadOnly = false;
            cmbStatus.DisplayMember = "Name";
            cmbStatus.ValueMember = "CaseStatusInt";
            cmbStatus.HeaderText = "Case Status";
            cmbStatus.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;


            DataGridViewButtonColumn btnEdit = new DataGridViewButtonColumn();
            btnEdit.HeaderText = "";
            btnEdit.Name = "Edit";
            btnEdit.Text = "Edit";
            btnEdit.UseColumnTextForButtonValue = true;
            btnEdit.Width = 50;

            gvOnTab.CellClick += new DataGridViewCellEventHandler(gvOnTab_CellClick);

            DataGridViewButtonColumn btnDelete = new DataGridViewButtonColumn();
            btnDelete.HeaderText = "";
            btnDelete.Name = "Delete";
            btnDelete.Text = "Delete";
            btnDelete.UseColumnTextForButtonValue = true;
            btnDelete.Width = 50;

            newColIndex = gvOnTab.Columns.Add("ComplaintId", "ComplaintId");
            gvOnTab.Columns[newColIndex].DataPropertyName = "ComplaintId";
            gvOnTab.Columns[newColIndex].ReadOnly = true;

            newColIndex = gvOnTab.Columns.Add("RecievedTime", "Recieved");
            gvOnTab.Columns[newColIndex].DataPropertyName = "RecievedTime";
            gvOnTab.Columns[newColIndex].ReadOnly = true;
            
            if (gvOnTab.Name == "gvAllCases") gvOnTab.Columns.Add(cmbStatus);
            gvOnTab.Columns.Add(cmbWhereFrom);



            newColIndex = gvOnTab.Columns.Add("CustomerName", "Customer");
            gvOnTab.Columns[newColIndex].DataPropertyName = "CustomerName";

            //newColIndex = gvOnTab.Columns.Add("CustomerSecondName", "Customer Last name");
            //gvOnTab.Columns[newColIndex].DataPropertyName = "CustomerSecondName";

            newColIndex = gvOnTab.Columns.Add("Description", "Description");
            gvOnTab.Columns[newColIndex].DataPropertyName = "Description";

            gvOnTab.Columns.Add(btnEdit);
            gvOnTab.Columns.Add(btnDelete);

            gvOnTab.Columns["CustomerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            gvOnTab.Columns["RecievedTime"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            gvOnTab.Columns["Description"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            gvOnTab.Columns["TicketId"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            gvOnTab.Columns["ComplaintId"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
        }

        private void ExitProgram ( ) {
            if( PromptSave ) {
                if( DialogResult.Yes == MessageBox.Show("You have unsaved changes. Do you want to save your changes before exiting the application?", Application.ProductName, MessageBoxButtons.YesNo) ) {
                    SaveToFile();
                }
            }

        }

        private void CountRows ( ) {
            lblStripRowCount.Text = "Displaying " + m_activeGrid.RowCount + @"/" + cdAccess.CaseItem.Rows.Count + " rows";
        }

        private bool OpenFile ( ) {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Title = "Open Case Manager File";
            //fdlg.InitialDirectory = @"c:\";
            openFile.Filter = "Case manager files (*.cmf)|*.cmf|All files (*.*)|*.*";
            openFile.FilterIndex = 1;
            openFile.RestoreDirectory = true;
            if( openFile.ShowDialog() == DialogResult.OK ) {
                this.Cursor = Cursors.WaitCursor;
                cdAccess = new CaseDataAccess(openFile.FileName);
                PopulateCases();
                m_currentFile = openFile.FileName;
                saveToolStripMenuItem.Enabled = false;
                this.Cursor = Cursors.Default;
                return true;
            }
            return false;
        }

        private bool SaveToFile ( ) {
            SaveFileDialog saveFile = new SaveFileDialog();
            //use some kind of initial directory here...
            saveFile.Filter = "Case manager files (*.cmf)|*.cmf|All files (*.*)|*.*";
            saveFile.FilterIndex = 1;
            saveFile.RestoreDirectory = true;

            if( saveFile.ShowDialog() == DialogResult.OK ) {
                this.Cursor = Cursors.WaitCursor;
                //maybe save the file location to a recently -register
                cdAccess.WriteCaseData(saveFile.FileName);
                m_currentFile = saveFile.FileName;
                PromptSave = false;
                this.Cursor = Cursors.Default;
                return true;
            }
            return false;
        }

        #region Events

        private void CaseManager_FormClosing ( object sender, FormClosingEventArgs e ) {
            ExitProgram();
        }
        
        private void btnNew_Click ( object sender, EventArgs e ) {
            frmCaseProperties prop = new frmCaseProperties(ref cdAccess, CaseAction.New);
            prop.ShowDialog(this);
            //m_hasUnchangedCases = true;
            //saveToolStripMenuItem.Enabled = true;
        }

        private void tabCases_Selected ( object sender, TabControlEventArgs e ) {
            if( tabCases.SelectedTab == tabAll ) m_activeGrid = gvAllCases;
            else if( tabCases.SelectedTab == tabCustomerContacted )
                m_activeGrid = gvCustomerContacted;
            else if( tabCases.SelectedTab == tabNew )
                m_activeGrid = gvNewCases;
            else if( tabCases.SelectedTab == tabPendingRepair )
                m_activeGrid = gvPendingRepair;
            else if( tabCases.SelectedTab == tabPendingApproval )
                m_activeGrid = gvPendingApproval;
            else if( tabCases.SelectedTab == tabPendingDelivery )
                m_activeGrid = gvPendingDelivery;
            else if( tabCases.SelectedTab == tabInProgress )
                m_activeGrid = gvInProgress;
            else if( tabCases.SelectedTab == tabFollowUp )
                m_activeGrid = gvFollowUp;
            else if( tabCases.SelectedTab == tabClosed )
                m_activeGrid = gvClosed;
            CountRows();
        }

        #region DataGridView Events
        //Fired when a cell has been clicked on. Used for buttons in grid
        void gvOnTab_CellClick ( object sender, DataGridViewCellEventArgs e ) {

            if( e.RowIndex < 0 ) return; //exit if no row selected

            if( e.ColumnIndex == m_activeGrid.Columns["Edit"].Index ) {
                //Casting current row into a tblCaseRow
                CaseDataAccess.CaseItemRow tmp =
                    (CaseDataAccess.CaseItemRow)
                    ((DataRowView) m_activeGrid.CurrentRow.DataBoundItem).Row;
                CaseRow tmpcRow = new CaseRow(tmp);
                frmCaseProperties prop = new frmCaseProperties(tmpcRow, ref cdAccess, CaseAction.Update);

                prop.StartPosition = FormStartPosition.CenterParent;
                prop.ShowDialog(this);
                //prop.ShowDialog(this.ParentForm);
                //m_hasUnchangedCases = true;
                //saveToolStripMenuItem.Enabled = true;
            }
            else if( e.ColumnIndex == m_activeGrid.Columns["Delete"].Index ) {
                if( DialogResult.Yes == MessageBox.Show("Are you sure you want to delete the selected case?", Application.ProductName, MessageBoxButtons.YesNo) ) {
                    //Casting current row into a tblCaseRow
                    CaseDataAccess.CaseItemRow tmp =
                        (CaseDataAccess.CaseItemRow)
                        ((DataRowView) m_activeGrid.CurrentRow.DataBoundItem).Row;
                    CaseRow tmpcRow = new CaseRow(tmp);
                    cdAccess.DeleteCaseRow(tmpcRow);
                    PromptSave = true;
                }
            }
        }


        //Fired when a cell has been edited
        private void tabCases_CellParsing ( object sender, DataGridViewCellParsingEventArgs e ) {
            PromptSave = true;
        }
        #endregion

        #region SearchText Events

        private void SearchFilter_TextChanged ( object sender, EventArgs e ) {
            ((CaseDataView) m_activeGrid.DataSource).RowFilter = ((TextBox) sender).Text;
            CountRows();
        }

        #endregion

        #region ToolStrip Events
        private void openToolStripMenuItem_Click ( object sender, EventArgs e ) {
            if( PromptSave ) {
                if( DialogResult.Yes == MessageBox.Show("You have unsaved changes. Do you want to save your changes before opening a new file?", Application.ProductName, MessageBoxButtons.YesNo) ) {
                    SaveToFile();
                    return;
                }
            }
            OpenFile();
        }

        private void exitToolStripMenuItem_Click ( object sender, EventArgs e ) {
            //ExitProgram(); save prompt is now handled by FormClosing event
            Application.Exit();
        }

        private void saveToolStripMenuItem_Click ( object sender, EventArgs e ) {
            //TODO: Check if file exist first
            cdAccess.WriteCaseData(m_currentFile);
            PromptSave = false;
        }

        private void saveAsToolStripMenuItem_Click ( object sender, EventArgs e ) {
            SaveToFile();
        }

        private void closeToolStripMenuItem_Click ( object sender, EventArgs e ) {
            if( PromptSave ) {
                if( DialogResult.Yes == MessageBox.Show("You have unsaved changes. Do you want to save your changes before closing?", Application.ProductName, MessageBoxButtons.YesNo) ) {
                    SaveToFile();
                }
            }
            cdAccess = new CaseDataAccess();
            PopulateCases();
        }

        private void aboutCaseManagerToolStripMenuItem_Click ( object sender, EventArgs e ) {
            TaskManager.frmAbout aboutBox = new TaskManager.frmAbout();
            aboutBox.ShowDialog();

        }


        #endregion

        #endregion

    }

}